import global from './global.js';
import { pickWorldPositionByMouse, toDegrees, vector3Offset } from './common.js';
let cache = {
	upscaleCount: 1,
	time: 510,
	shutterSpeed: 60,
	fancingList: [],
	BuildingOutlineList: [],
	meshLayerList: [],
};

//获取是否为桌面端 desktop：桌面端、web：网页端
export function getViewName(viewName) {
	viewName == 'desktop' && (window.isDeskTop = true);
}

/**
 * 数生sdk鉴权
 */
export function setAuthorize() {
	GlobalViewer.setAuthorizedUrl(
		'https://www.dataarche.com:8062/authentic/license?t=2023-03-21T11:09:37.152' // 欣横鉴权
	);
}

// 新引擎爆闪和模型拖影
export function useFSR(isFSR = true) {
	SSmap.useFSR(isFSR);
}

//加载Arcgis影像(DOM) type = mapServer
export function addArcGisImagery(url) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	globe.lightingEnabled = true;
	let imageLayer = globe.addArcGisMapServerImageryLayer(url);
	global.imageLayer = imageLayer;
	return imageLayer;
}

//加载天地图影像(DOM) type = tianditu
// export function addTiandituImagery(url) {
// 	// if (!global.imageLayer) {
// 	let scene = window.viewer.scene;
// 	let globe = scene.globe;
// 	globe.lightingEnabled = true;
// 	let imageLayer = new SSmap.TiandituImageryLayer();
// 	imageLayer.url = url ? url : 'https://t2.tianditu.gov.cn/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=789e558be762ff832392a0393fd8a4f1';
// 	imageLayer.useWebMercator = false;
// 	imageLayer.tileWidth = 256;
// 	imageLayer.tileHeight = 256;
// 	imageLayer.minimumLevel = 1;
// 	imageLayer.maximumLevel = 17;
// 	imageLayer.hasAlphaChannel = false;
// 	imageLayer.isLabel = false;
// 	imageLayer.componentComplete();
// 	global.imageLayer = imageLayer;
// 	return imageLayer;
// 	// }
// }
export function addTiandituImagery(url) {
	if (!window.nowLayer) {
		let scene = window.viewer.scene;
		let globe = scene.globe;
		globe.lightingEnabled = true;
		window.nowLayer = new SSmap.TiandituImageryLayer();
		window.nowLayer.url = 'https://t4.tianditu.gov.cn/DataServer?T=img_c&x={x}&y={y}&l={z}&tk=f6362cc90bd27c5445afaae2febf5745';
		window.nowLayer.useWebMercator = false; //使用卡托否
		window.nowLayer.tileWidth = 256; //瓦片宽度
		window.nowLayer.tileHeight = 256; //瓦片长度
		window.nowLayer.minimumLevel = 1; //最小层级
		window.nowLayer.maximumLevel = 17; //最大层级
		window.nowLayer.hasAlphaChannel = false; //使用阿尔法否
		window.nowLayer.isLabel = false; //标签否 用于影像和标记一起使用时，影像的isLabel设置为false,标记的isLabel设置为true
		window.nowLayer.componentComplete(); //创建
	}
}

//加载丰图wmts影像(DOM) type = wmts
export function addWMTSLayer(url) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	globe.lightingEnabled = false;
	let imageLayer = globe.addWmsImageryLayer(url);
	global.imageLayer = imageLayer;
	return imageLayer;
}

// 移除影像
export function removeImageLayer(type) {
	if (global.imageLayer) {
		if (type == 'tianditu') {
			global.imageLayer.delete();
		} else {
			global.imageLayer.show = false;
		}
		global.imageLayer = null;
	}
}

// 加载树数据
export function addForest(info) {
	let trees = new SSmap.Forest();
	trees.loadFromGeojson(info.geojsonUrl);
	trees.loadFromTree(info.treeUrl, true); //加载speedTree树种
	trees.setHightDef(info.height || 1.0);
	let treeEntity = new SSmap.Entity();
	treeEntity.addComponent(trees);
	treeEntity.parent = SSmap.Entity.root();
}

//加载3dtiles数据(默认深圳市白模)
export function addTileset(url, key) {
	let scene = window.viewer.scene;
	let tileset = new SSmap.Tileset(url);
	tileset.clipLevelOfDetail = true;
	if (key) {
		tileset.setHeader('layerKey', key);
	}
	let rotation = SSmap.Quaternion.fromEulerAngles(0, 0, 0); //四元数 控制旋转
	let matrix3 = rotation.toRotationMatrix();
	// let offsetValue = offset || SSmap.Vector3.create(0, 0, -20); //偏移量
	var entity = new SSmap.Entity();
	entity.addComponent(tileset);
	entity.objectName = name || 'model';
	scene.addEntity(entity);
	tileset.readyPromise.then(function () {
		const center = tileset.rectangle.center();
		const cord = center.toDegrees();
		let position = SSmap.Cartographic.fromDegrees(cord.longitude, cord.latitude, 1000);
		window.viewer.scene.mainCamera.cameraController().flyToCartographic(position, 3, 360, -90, 0);
	});
	return entity;
}

export function showWhiteTiles(boolean) {
	let url = boolean ? 'data/white_3DTILES/tileset.json' : 'data/HN_3DTILES/JZ_3DTILES/tileset.json';
	const temp = window.tiles3D;
	window.tiles3D = addTileset(window.location.href + url, '222');
	window.viewer.scene.rootEntity.childEntities.get(10).delete();
}

//加载白模数据
export function addTilesetLayer({ url }) {
	let tilesetLayer = new SSmap.TilesetLayer();
	tilesetLayer.url = url;
	// tilesetLayer.color = SSmap.Color.fromRgb(255, 251, 240, 255);
	// tilesetLayer.renderStyle = SSmap.RenderStyle.ColorStyle;
	// tilesetLayer.maximumMemoryUsage = 1024;
	tilesetLayer.componentComplete();
	let camera = window.viewer.scene.mainCamera.cameraController();
	camera.flyToRectangle(tilesetLayer.tileset().rectangle, 2, 0, -88, 0);

	// let key = global.tilesetLayer.add(tilesetLayer);
	// if (unlit) {
	// 	changeShadingModel(tilesetLayer.tileset());
	// }
	// if (mount) {
	// 	this.setDefault(key);
	// }
	// callback(key);
}
//设置默认的tilesetLayer
export function setDefault(key) {
	global.modelLayer = global.tilesetLayer.get(key);
}
export function removeTilesetLayer(id) {
	let val = global.tilesetLayer.get(id);
	if (!val) return;
	global.tilesetLayer.remove(id);
}

export function removeAllTilesetLayer() {
	global.tilesetLayer.removeAll();
}

//加载高程数据(DEM)
export function addTerrain(url, key) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	let terrainProvider = new SSmap.GlobeTerrainProvider(url);
	terrainProvider.setHeader('layerKey', key);
	globe.terrainProvider = terrainProvider;
}

export function addUrlTemplateImageryProvider(params) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	let rectangle = SSmap.Rectangle.fromDegrees(-180, -90, 180, 90);
	var imageryProvider = new SSmap.UrlTemplateImageryProvider(
		params.url + '/{z}/{x}/{y}.png', // url
		true, // useWebMercator
		21, // maximumLevel
		0, // minimumLevel
		256, // tileWidth
		256, // tileHeight
		true // hasAlphaChannel
	);
	imageryProvider.setHeader('layerKey', params.key);
	var imageryLayer = new SSmap.ImageryLayer(imageryProvider, rectangle);
	globe.addImageryLayer(imageryLayer);
}
// 加载默认高层(全球高度为0)
export function setDefaultTerrain() {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	globe.setDefaultTerrain();
}
//我的位置
export function goToHome(position, orientation) {
	let scene = window.viewer.scene;
	let camera = scene.mainCamera;
	let cameraController = camera.cameraController();
	cameraController.enableTilt = true;
	cameraController.enableLook = true;
	position = position || {
		longitude: 114.255838,
		latitude: 22.725976,
		height: 155.3749909575039,
	};
	orientation = orientation || {
		heading: 283.6400050847913,
		pitch: -19.551272822842073,
		roll: 0,
		duration: 2,
	};
	position = SSmap.Cartographic.fromDegrees(position.longitude, position.latitude, position.height).toVector3();
	cameraController.flyTo(position, orientation.duration, orientation.heading, orientation.pitch, orientation.roll);
}
export function changeShadingModel(tileset, noUnlit) {
	tileset.readyPromise.then(function () {
		if (tileset.entity) {
			tileset.entity.travalRenderers(function (renderer) {
				// !noUnlit && (renderer.material.shadingModel = SSmap.ShadingModel.Unlit) //光照，无
				// renderer.material.shadingModel = SSmap.ShadingModel.Unlit
				changeMaterialLight(renderer);
			});
		}
	});
	tileset.contentLoaded(function (root) {
		root.travalRenderers(function (renderer) {
			// !noUnlit && (renderer.material.shadingModel = SSmap.ShadingModel.Unlit) //光照，无
			// renderer.material.shadingModel = SSmap.ShadingModel.Unlit
			changeMaterialLight(renderer);
		});
	});
}

export function changeMaterialLight(renderer) {
	if (renderer.material) {
		renderer.material.roughness = 0.8;
		renderer.material.reflectance = 0;
		renderer.material.metallic = 0;
	}
}

//开启键盘控制
export function setFPSController(flag) {
	let FPSCtrl = new SSmap.FPSController();
	FPSCtrl.setAction(flag);
}

//设置字体
export function setFont(font) {
	SSmap.FontManager.setFont(font);
}
//设置系统时间
export function setTimeSystem({ year, month, day, hours, min }) {
	let timeSystem = window.viewer.timeSystem;
	year && timeSystem.setYear(year);
	month && timeSystem.setMonth(month + 1);
	day && timeSystem.setDay(day);
	hours && timeSystem.setHour(hours);
	min && timeSystem.setMinute(min);
	return;
}

// 获取相机位置（）
export function getCameraCartographic(callback) {
	let scene = window.viewer.scene;
	let camera = scene.mainCamera;
	let cameraController = camera.cameraController();
	let position = cameraController.positionCartographic.toDegrees();
	let cartographic = {
		longitude: position.longitude,
		latitude: position.latitude,
		height: position.height,
	};
	let heading = cameraController.heading;
	let pitch = cameraController.pitch;
	let roll = cameraController.roll;
	heading = toDegrees(heading); // 弧度转角度
	pitch = toDegrees(pitch);
	roll = toDegrees(roll);
	// goToPosition({ cartographic, heading, pitch, roll, duration: 2 });
	// 返回的都是角度
	callback({ cartographic, heading, pitch, roll });
}

// 相机飞往指定位置
export function goToPosition({ cartographic, heading, pitch, roll, duration }) {
	let scene = window.viewer.scene;
	let camera = scene.mainCamera;
	let cameraController = camera.cameraController();
	let position = SSmap.Cartographic.create(cartographic.longitude, cartographic.latitude, cartographic.height);
	cameraController.flyToCartographic(position, duration, heading, pitch, roll);
}
// 二三维切换
export function switchDimension() {
	let scene = window.viewer.scene;
	let camera = scene.mainCamera;
	var cameraController = camera.cameraController();
	const degrees = cameraController.transform.position.toCartographic().toDegrees();
	let pitchs = null;
	let distance = degrees.height.toFixed(0);
	if (cameraController.enableTilt) {
		pitchs = -90;
	} else {
		pitchs = -30;
	}

	//相机射线获取中心点
	const point = pickGlobeCenterPoint();
	console.log(point, 'point');
	if (!point) {
		console.log('未能获取到地图中心点，试试视角调低');
		return;
	}

	//利用三角函数，根据500米距离和俯仰角（opt.pitch）计算正北方向 观察点（相机）的偏移值
	let Yoffset = Math.sin(((90 + pitchs) * Math.PI) / 180) * distance;
	let Zoffset = Math.cos(((90 + pitchs) * Math.PI) / 180) * distance;

	//根据上述偏移值，重新获取偏移后的坐标（相机位置）
	let destination = vector3Offset(point, {
		offsetY: -Yoffset,
		offsetZ: Zoffset,
	});
	cameraController.flyTo(destination, 2, 0, pitchs, 0);
	cameraController.enableTilt = !cameraController.enableTilt;
	cameraController.enableLook = !cameraController.enableLook;
}

//获取地图中心点
export function pickGlobeCenterPoint() {
	const canvas = window.viewer.canvas;
	const shardHeight = canvas.height / 10;
	for (let i = 0; i <= 10; i++) {
		const x = canvas.width / 2;
		const y = shardHeight * i;
		const point = pickWorldPositionByMouse(x, y);
		if (point != null) {
			const newClientHeight = (canvas.height - y) / 2 + y;
			const newPoint = pickWorldPositionByMouse(x, newClientHeight);
			return newPoint;
		}
	}
}

//打点偏移视角移动
export function flyToNewModel(point, distanceNum, pitchNum, time) {
	const camera = window.viewer.scene.mainCamera.cameraController();
	let distance = distanceNum || 100;
	const headings = (180 / Math.PI) * camera.heading;
	let rolls = (180 / Math.PI) * camera.roll;
	if (parseInt(rolls).toString().includes('18') || parseInt(rolls).toString().includes('17')) rolls -= 180;
	let pitchs = -(pitchNum || Math.abs((180 / Math.PI) * camera.pitch));
	//利用三角函数，根据500米距离和俯仰角（opt.pitch）计算正北方向 观察点（相机）的偏移值
	let Xoffset = Math.sin(((180 + headings) * Math.PI) / 180) * Math.abs(distance * Math.sin(((90 + pitchs) * Math.PI) / 180));
	let Yoffset = Math.cos(((180 + headings) * Math.PI) / 180) * Math.abs(distance * Math.sin(((90 + pitchs) * Math.PI) / 180));
	let Zoffset = Math.cos(((90 + pitchs) * Math.PI) / 180) * distance;
	//根据上述偏移值，重新获取偏移后的坐标（相机位置）
	let destination = vector3Offset(point, {
		offsetX: Xoffset,
		offsetY: Yoffset,
		offsetZ: Zoffset,
	});
	camera.flyTo(destination, time || 2, headings, pitchs, rolls);
}

// 回到现实时间
export function resetTimeSystem() {
	let timeSystem = window.viewer.timeSystem;
	let date = new Date();
	date.getDate();
	timeSystem.setYear(date.getFullYear());
	timeSystem.setMonth(date.getMonth() + 1);
	timeSystem.setDay(date.getDate());
	timeSystem.setHour(date.getHours());
	timeSystem.setMinute(date.getMinutes());
}

//相机视角开启
export function enableCameraInputs(bool) {
	let scene = window.viewer.scene;
	let cameraController = scene.mainCamera.cameraController();
	cameraController.enableInputs = bool;
}

// 全球光
export function lightingEnabled(bool) {
	let scene = window.viewer.scene;
	let globe = scene.globe;
	globe.lightingEnabled = bool;
	globe.opacity = bool ? 1 : 0.6;
}

export function pickTileset(posX, posY, cb) {
	let scene = window.viewer.scene;
	let ray = scene.mainCamera.screenPointToRay(posX, posY);
	let hit = new SSmap.RaycastHit();
	let data = null;
	if (scene.raycast(ray, hit)) {
		const feature = scene.getFeatureByMouse();
		if (feature) {
			scene.setFeatureSelectedColor(SSmap.Color.fromRgb(255, 0, 0, 255));
			scene.setSelectedFeature(feature);
			let nameList = feature.propertyNames();
			let size = nameList.size();
			if (size > 0) {
				let json = {};
				for (let i = 0; i < size; i++) {
					let key = nameList.get(i);
					let value = feature.getProperty(key);
					json[key] = value;
				}
				data = json;
			}
		} else {
			resetPickTileset();
		}
		hit.delete();
	}
	cb(data);
}

export function resetPickTileset() {
	let scene = window.viewer.scene;
	scene.setSelectedFeature(null);
}

// 键盘控制
const keysControls = {
	resetInputs(flag) {
		let scene = GlobalViewer.scene;
		let camera = scene.mainCamera;
		let cameraController = camera.cameraController();
		cameraController.enableInputs = flag;
	},
	translate(radian, direction, speed = 2) {
		let scene = GlobalViewer.scene;
		let camera = scene.mainCamera;
		let position = camera.transform.position;
		let cameraController = camera.cameraController();
		let heading = cameraController.heading; //朝向
		let pitch = cameraController.pitch; //俯仰角
		if (direction == 's') {
			pitch = -pitch;
		}

		radian += heading;

		camera.transform.position = vector3Offset(position, {
			offsetX: Math.sin(radian) * speed,
			offsetY: Math.cos(radian) * speed,
			offsetZ: direction ? Math.sin(pitch) * speed : 0,
		});
	},
	rotate(left = 0, up = 0, speed = 800) {
		let scene = GlobalViewer.scene;
		let camera = scene.mainCamera;
		let position = camera.transform.position;
		let cameraController = camera.cameraController();
		let heading = cameraController.heading; //朝向
		let pitch = cameraController.pitch; //俯仰角
		let roll = cameraController.roll; //翻滚角

		let delta = Math.PI / 4 / speed; //默认800px旋转45度
		let rotateLeft = left * delta;
		let rotateUp = up * delta; //俯仰角

		heading += rotateLeft;
		pitch += rotateUp;

		cameraController.setView(position.toCartesian3(), heading, pitch, roll);
	},
};
export { keysControls };

export function defaultSceneSetting() {
	const defaultScene = {
		autoExposure: false,
		contrast: 1.1,
		exposure: 1,
		saturation: 1,
		sharpen: 0.5,
		toneCurveAmount: 0.3,
		bloomValue: 0.8,
		whiteTemp: 6820,
		blueCorrection: 0.6000000238418579,
		brightThreshold: 1.5,
		antiAliasing: 'TAA',
		indirectLight: 10666,
		hdrDiffuseIntensity: 1,
		hdrSpecularIntensity: 1,
		hdrRotation: 120,
		sunintensity: 100000,
		aoQuality: 2,
		aoRadius: 3.6,
		aoAmount: 2.200000047683716,
		aoFadeIn: 0.6570000052452087,
		atmIntensity: 266666,
		atmInscatterAmount: 15,
		upscaleCount: 2,
		time: 931,
		shutterSpeed: 58,
	};
	SceneSetting.set(defaultScene);
}

export const SceneSetting = {
	get(cb) {
		// 渲染相关
		let renderSystem = GlobalViewer.renderSystem;
		// HDR后期调色参数控制对象
		let postRendering = renderSystem.postRendering();
		//环境光对象
		let indirectLightObj = GlobalViewer.scene.indirectLight;
		// 大气层对象
		let atmosphere = GlobalViewer.scene.atmosphere;
		// 太阳对象
		let sun = GlobalViewer.scene.sun;
		// 相机对象
		// let camera = GlobalViewer.scene.mainCamera;
		//   环境光遮挡
		let ssao = renderSystem.ssao;
		let antiAliasingList = {
			TAA: SSmap.AntiAliasing.TAA,
			FXAA: SSmap.AntiAliasing.FXAA,
			NoAA: SSmap.AntiAliasing.NoAA,
		};
		let antiAliasing = 'TAA';
		for (let key in antiAliasingList) {
			if (renderSystem.antiAliasing == antiAliasingList[key]) {
				antiAliasing = key;
			}
		}
		let obj = {
			// 自动曝光
			autoExposure: postRendering.autoExposure,
			// 对比度
			contrast: postRendering.contrast,
			// 曝光度
			exposure: postRendering.exposure,
			//    饱和度
			saturation: postRendering.saturation,
			//    锐度
			sharpen: postRendering.sharpen,
			//  色调曲线数量
			toneCurveAmount: postRendering.toneCurveAmount,
			// 眩光值
			bloomValue: postRendering.bloomValue,
			// 色温
			whiteTemp: postRendering.whiteTemp,
			// 伽马值
			gamma: postRendering.gamma,
			// 亮度
			brightness: postRendering.brightness,
			// 色調
			hue: postRendering.hue,
			// 透明度
			alpha: postRendering.alpha,
			//    蓝光修正
			blueCorrection: postRendering.blueCorrection,
			// 亮度阈值
			brightThreshold: postRendering.brightThreshold,
			// 反锯齿方式
			antiAliasing: antiAliasing,
			// 强度
			indirectLight: indirectLightObj.intensity,
			//    漫反射强度
			hdrDiffuseIntensity: indirectLightObj.diffuseIntensity, //漫反射强度
			//    高光强度
			hdrSpecularIntensity: indirectLightObj.specularIntensity, //镜面反射强度
			//    角度
			hdrRotation: indirectLightObj.rotation, //旋转值
			//    光照强度
			sunintensity: sun.intensity,
			// 质量
			aoQuality: ssao.quality,
			//  半径
			aoRadius: ssao.radius,
			//  数量
			aoAmount: ssao.amount,
			//  渐入时间
			aoFadeIn: ssao.fadeIn,
			// 天空亮度
			atmIntensity: atmosphere.intensity,
			// 大气散射
			atmInscatterAmount: atmosphere.inscatterAmount,
			// 渲染质量
			upscaleCount: cache.upscaleCount,
			// 时间（分钟）
			time: cache.time, //08:30
			// 快门时间 camera.shutterSpeed
			shutterSpeed: cache.shutterSpeed,
		};
		cb(obj);
	},
	set({
		// 自动曝光
		autoExposure,
		// 对比度
		contrast,
		// 曝光度
		exposure,
		//    饱和度
		saturation,
		//    锐度
		sharpen,
		//  色调曲线数量
		toneCurveAmount,
		// 眩光值
		bloomValue,
		// 色温
		whiteTemp,
		//伽马值
		gamma,
		//亮度
		brightness,
		//透明度
		alpha,
		// 色彩
		hue,
		//    蓝光修正
		blueCorrection,
		// 亮度阈值
		brightThreshold,
		// 反锯齿方式
		antiAliasing,
		// 强度
		indirectLight,
		//    漫反射强度
		hdrDiffuseIntensity,
		//镜面反射强度
		hdrSpecularIntensity,
		//    角度
		hdrRotation, //旋转值
		//    光照强度
		sunintensity,
		// 质量
		aoQuality,
		//  半径
		aoRadius,
		//  数量
		aoAmount,
		//  渐入时间
		aoFadeIn,
		// 天空亮度
		atmIntensity,
		// 大气散射
		atmInscatterAmount,
		// 渲染质量
		upscaleCount,
		// 时间
		time,
		// 快门时间
		shutterSpeed,
	}) {
		// let tdtLayer = window.nowLayer.layer()
		// tdtLayer.gamma = gamma ? gamma : 1 //伽马值
		// tdtLayer.alpha = alpha ? alpha : 1 //透明度
		// tdtLayer.brightness = brightness ? brightness : 1 //亮度
		// tdtLayer.hue = hue ? hue : 0.3//色彩
		// tdtLayer.saturation = saturation ? saturation : 1
		// tdtLayer.contrast = contrast ? contrast : 1//对比度

		// 渲染相关
		let renderSystem = GlobalViewer.renderSystem;
		// HDR后期调色参数控制对象
		let postRendering = renderSystem.postRendering();
		//环境光对象
		let indirectLightObj = GlobalViewer.scene.indirectLight;
		// 大气层对象
		let atmosphere = GlobalViewer.scene.atmosphere;
		// 太阳对象
		let sun = GlobalViewer.scene.sun;
		//   环境光遮挡
		let ssao = renderSystem.ssao;
		// 相机对象
		let camera = GlobalViewer.scene.mainCamera;
		// 时间系统
		let timeSystem = GlobalViewer.timeSystem;
		if (time) {
			cache.time = time;
			timeSystem.setHour(parseInt(time / 60));
			timeSystem.setMinute(parseInt(time % 60));
		}
		if (shutterSpeed) {
			// 快门时间
			camera.shutterSpeed = 1 / shutterSpeed;
			cache.shutterSpeed = shutterSpeed;
		}
		// 天空亮度
		atmIntensity && (atmosphere.intensity = atmIntensity);
		// 大气散射
		atmInscatterAmount && (atmosphere.inscatterAmount = atmInscatterAmount);
		// 自动曝光
		autoExposure && (postRendering.autoExposure = autoExposure);
		// 对比度
		contrast && (postRendering.contrast = contrast);
		// 曝光度
		exposure && (postRendering.exposure = exposure);
		//    饱和度
		saturation && (postRendering.saturation = saturation);
		//    锐度
		sharpen && (postRendering.sharpen = sharpen);
		//  色调曲线数量
		toneCurveAmount && (postRendering.toneCurveAmount = toneCurveAmount);
		// 眩光值
		bloomValue && (postRendering.bloomValue = bloomValue);
		// 色温
		whiteTemp && (postRendering.whiteTemp = whiteTemp);
		//    蓝光修正
		blueCorrection && (postRendering.blueCorrection = blueCorrection);
		// 亮度阈值
		brightThreshold && (postRendering.brightThreshold = brightThreshold);
		// 渲染质量
		if (upscaleCount) {
			postRendering.setUpscaleCount(Number(upscaleCount));
			cache.upscaleCount = Number(upscaleCount);
		}
		// 反锯齿方式
		antiAliasing && (renderSystem.antiAliasing = SSmap.AntiAliasing[antiAliasing]);
		// 强度
		indirectLight && (indirectLightObj.intensity = indirectLight);
		//    漫反射强度
		hdrDiffuseIntensity && (indirectLightObj.diffuseIntensity = hdrDiffuseIntensity); //漫反射强度
		//    高光强度
		hdrSpecularIntensity && (indirectLightObj.specularIntensity = hdrSpecularIntensity); //镜面反射强度
		//旋转值
		hdrRotation && (indirectLightObj.rotation = hdrRotation);
		//    光照强度
		sunintensity && (sun.intensity = sunintensity);
		// 质量
		aoQuality && (ssao.quality = aoQuality);
		//  半径
		aoRadius && (ssao.radius = aoRadius);
		//  数量
		aoAmount && (ssao.amount = aoAmount);
		//  渐入时间
		aoFadeIn && (ssao.fadeIn = aoFadeIn);
	},
};

export const imageSetting = {
	get(isArcgis, cb) {
		// 获取当前图层
		const postRendering = isArcgis ? window.nowLayer : window.nowLayer.layer();
		// const postRendering = window.nowLayer
		// 构建包含渲染参数的对象
		const obj = {
			saturation: postRendering.saturation,
			gamma: postRendering.gamma,
			brightness: postRendering.brightness,
			hue: postRendering.hue,
			alpha: postRendering.alpha,
			contrast: postRendering.contrast,
		};

		// 调用回调函数传递对象
		cb(obj);
	},
	set(
		{
			// 伽马值
			gamma,
			// 亮度
			brightness,
			// 透明度
			alpha,
			// 色彩
			hue,
			saturation,
			contrast,
		},
		isArcgis
	) {
		const tdtLayer = isArcgis ? window.nowLayer : window.nowLayer.layer();
		// const tdtLayer = window.nowLayer
		// 设置默认值
		const defaults = {
			gamma: gamma || 1,
			alpha: alpha || 1,
			brightness: brightness || 1,
			hue: hue || 0.3,
			saturation: saturation || 1,
			contrast: contrast || 1,
		};

		// 应用设置
		Object.assign(tdtLayer, defaults);
	},
};
export function cameraFlyToRectangle(
	boundingBox,
	orientation = {
		heading: 0,
		pitch: -80,
		roll: 0,
	},
	duration = 1
) {
	let cameraController = GlobalViewer.scene.mainCamera.cameraController();
	let ractangle = SSmap.Rectangle.fromDegrees(boundingBox.west, boundingBox.south, boundingBox.east, boundingBox.north);

	cameraController.flyToRectangle(ractangle, duration, orientation.heading, orientation.pitch, orientation.roll);
}

// 获取影像图
export function getImageLayer(id, cb) {
	let imageryLayer = null;
	imageryLayer = global.layerList.get(id);
	window.nowLayer = imageryLayer;
	cb && cb(imageryLayer);
	return imageryLayer;
}
